#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: 李吉凯
@Email: lijk34925@hundsun.com
@Time: 2022/5/12 10:31
@File: 公共方法.py
"""
import re
import time
import traceback
from copy import copy

from qturboframe.lib.utils.by import By
from qturboframe.lib.webdriver import SeleniumError

from BladeFerm.hui12_common.function import display_wait
from BladeFerm.hui2_app import FE
from BladeFerm.hui2_app.basic import open_child_system
from BladeFerm.Lib.Common import logger
from BladeFerm.hui2_app.hui2_lib.button import Button


def action_none(input_data=None, ui_expect=None):
    logger.info(f'input_data: {input_data}, ui_expect:{ui_expect}')


def open_menu(input_data=None, ui_expect=None):
    '''
    打卡菜单。 '客户风险评估/风险等级查询'
    :param input_data:
        {'子系统名称': '反洗钱系统', '菜单名称': '客户风险评估/风险等级查询'} 或者 {'菜单名称': '风险等级查询'}
    :param ui_expect:
    :return:
    '''
    #打开子系统
    child_sys_name = input_data.get('子系统名称', None)
    if child_sys_name:
        time.sleep(1)
        open_child_system(child_sys_name)
    # open_child_system('反洗钱系统')
    # 进入 风险等级查询 菜单
    menu_name = input_data.get('菜单名称')
    menu_name_list = menu_name.split('/')
    if len(menu_name_list) > 1:
        FE.menu().select(menu_name)
    else:
        FE.button(idname={'xpath': '//div[@class="h-layout-menu-item-wrap"]/div/span[text()="'+menu_name+'"]'}).click()
    # time.sleep(0.5)
    # 打开页面后，检查是否存在弹框
    msgBox = FE.msg_box(idname={By.CSS_SELECTOR: 'div.h-message'}, timeout=0.5)
    flag = msgBox.exist()
    if flag:
        content = msgBox.get_text()
        raise SeleniumError(f"检查出现错误弹框，内容为：{content}")



'''
标准模板二：
测试逻辑步骤：
    打开菜单: CommonScripts/common_util.py  open_menu(input_data=None, ui_expect=None)
    表单填充数据：./  risk_level_form_fill(input_data=None, ui_expect=None)
    结果校验：CommonScripts/步骤检查.py  check_table(input_data=None, ui_expect=None) 
Blade平台写用例时就写三步
'''


def arm_form_fill(input_data=None, ui_expect=None):
    '''
    表单填充的通用功能。
    :param input_data:
    :param ui_expect:
    :return:
    '''
    menu_name = input_data.pop("菜单名称", None)
    title_name = input_data.pop('表单项名称', None)
    # 表单填充数据　和　按钮操作标志
    retry_flag, query_flag = False, False
    index = 0
    max_retry = 3
    # 表单页面，下拉框滚动可能造成页面整体上移，导致元素不可用。刷新页面后重试。 2025-05-28
    while index < max_retry:
        if title_name:
            id_name_xpath = {
                By.XPATH: f'//div[contains(@class,"h-form-item")]/label[@title="{title_name}"]//ancestor::form'}
            search_form = FE.form(idname=id_name_xpath)
        else:
            id_name = {
                By.XPATH: '//div[@class="h-form-item-content"]/button/span[contains(text(),"查询")]//ancestor::form'}
            logger.info(f"id_name: {type(id_name)}, {id_name}")
            search_form = FE.form(idname=id_name)
        # 表单填入  流程管理界面的表单查询展开按钮名称为 高级，其他为更多 2025-3-25 修改
        search_form.button_option('重置')
        button_name = "高级" if menu_name and menu_name.startswith('流程管理') else '更多'
        search_form.button_option(button_name)
        data = copy(input_data)
        for key, value in input_data.items():
            if key == '行业':
                fill_job(key, value)
                data.pop(key)
            else:
                continue
        retry_flag = search_form.auto_fill_group(data)       # 表单填充数据，若填写失败，会返回重试标志为true
        query_flag = search_form.button_option('查询')        # 点击查询按钮，若按钮不可用会返回false
        index += 1
        if retry_flag and (not query_flag):
            FE.driver.refresh()
            display_wait({By.XPATH: '//form'}, 1, 10, FE.driver)
            logger.warning(f'刷新页面，重新填写表单')
        else:
            index = max_retry
    if retry_flag and (not query_flag):
        raise SeleniumError(f'刷新页面重试了{index}次，表单填写失败！')


def form_data_fill(input_data=None, ui_expect=None):
    """
    弹出的表单数据填充，适用于新增和修改场景
    :param input_data:
        操作：保存|取消|重置
        允许保存：是|否
    :return:
    """
    last_operate = input_data.pop('操作', '保存')
    save_flag = ui_expect.pop('允许保存', '是')
    # 步骤1：获取弹框元素
    layer_body_xpath = {By.XPATH: '//div[@class="h-modal-content" and not(contains(@style,"display: none"))]'}
    lay_body = FE.list(layer_body_xpath)
    display_wait(layer_body_xpath, flag=0, timeout=3, driver=lay_body.element)
    # 步骤2：点击重置
    FE.button('重置', father=lay_body.element).click()
    # 步骤3：获取弹框中的表单元素
    id_name_xpath = {By.XPATH: '//div[@class="h-modal-body"]//form'}
    data_form = FE.form(idname=id_name_xpath, father=lay_body.element)
    data_form.auto_fill_group(input_data)
    # 步骤5：点击保存
    if last_operate == '取消':
        FE.button(idname={By.XPATH: './/a[@class="h-modal-close"]/i'}, father=lay_body.element).click()
        return None
    elif last_operate == '重置':
        FE.button('重置', father=lay_body.element).click()
    elif last_operate == '保存':
        pass
    else:
        raise SeleniumError(f'未知的操作：{last_operate}')
    # 最好必定点击保存
    FE.button('保存', father=lay_body.element).click()
    # 步骤6：判断是否存在必填项字段校验
    if ui_expect:
        for key, value in ui_expect.items():
            div_xpath = f'//div[@class="verify-tip-inner" and contains(text(),"{value}")]'
            res = lay_body.fund_elements({By.XPATH: div_xpath})
            if not res:
                logger.info(f'{key} 必填项校验失败！')
                raise SeleniumError(f'{key} 必填项校验失败！')
            logger.info(f"{key} 必填项校验成功！")
    # 步骤7：判断是否保存成功
    time.sleep(0.1)
    add_result = display_wait(layer_body_xpath, flag=1, timeout=1, driver=FE.driver)
    if not add_result and save_flag == '是':
        logger.info(f'保存成功！')
    elif not add_result and save_flag == '否':
        err_1 = f'不符合预期：不允许保存，但是保存成功了！'
        logger.error(err_1)
        raise SeleniumError(err_1)
    elif add_result and save_flag == '否':
        FE.button(idname={By.XPATH: './/a[@class="h-modal-close"]/i'}, father=lay_body.element).click()
        logger.info(f'符合预期：不允许保存，不允许保存！')
    elif add_result and save_flag == '是':
        err_2 = f'不符合预期：允许保存，但是保存失败了！'
        logger.error(err_2)
        FE.button(idname={By.XPATH: './/a[@class="h-modal-close"]/i'}, father=lay_body.element).click()
        raise SeleniumError(err_2)
    else:
        logger.warning(f'存在其他结果？')


def switch_tab(input_data=None, ui_expect=None):
    '''
    切换tab页
    :param input_data: {'Tab页'： '基本信息'}
    :param ui_expect:  {'期望结果': '基本信息'}
    :return:
    '''
    # 打开目标tab页
    tab_list = FE.list(idname={By.CSS_SELECTOR: 'div.h-tabs-nav'})
    tab_list.foud_target(idname={By.CSS_SELECTOR: 'div.h-tabs-tab'})
    tab_list.click_target(input_data.get('Tab页'))
    # 检查是否切换到目标tab页
    # check_ele_text(ui_expect=ui_expect)


def scene_check(labelName,checkContent):
    '''
        labelName:下拉框前面的label名称
        checkContent: 下来框选择内容
    '''
    # FE.button(idname={
    #     'xpath': '//label[contains(text(),"'+labelName+'")]/ancestor::div[@class="h-row"]/descendant::span[@class="h-select-placeholder"]'}).click()
    FE.button(idname={
        'xpath': '//label[contains(text(),"'+labelName+'")]/ancestor::div[@class="h-row"]/descendant::i[contains(@class,"h-icon-unfold")]'}).click()
    if checkContent == "全选":
        FE.button(idname={
            'xpath': '//label[contains(text(),"' + labelName + '")]/ancestor::div[@class="h-row"]/descendant::span[text()="全选"]'}).click()
    elif "," in checkContent:
        str_list = re.split(",", checkContent)
        for i in str_list:
            FE.button(idname={
                'xpath': '//label[contains(text(),"' + labelName + '")]/ancestor::div[@class="h-row"]/descendant::li/span[contains(text(),"' + i + '")]'}).click()
    else:
        FE.button(idname={
            'xpath': '//label[contains(text(),"'+labelName+'")]/ancestor::div[@class="h-row"]/descendant::li/span[contains(text(),"'+checkContent+'")]'}).click()


def fill_job(labelName,text):
    '''
    行业
    '''
    FE.button(idname={'xpath':'//label[contains(text(),"行业")]/parent::div/descendant::span[@class="h-select-placeholder"]'}).click()
    FE.button(idname={'xpath':'//div[@class="h-select-dropdown"]/descendant::div/span[contains(text(),"'+text+'")]'}).click()


def tab_click(tab_name):
    FE.button(idname={'xpath':'//div[contains(@class, "h-tabs-tab") and contains(text(), "'+tab_name+'")]'}).click()
